from typing import List


class Solution:
    def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
        m, n = len(heights), len(heights[0])
        pacific, atlantic = set(), set()

        def dfs(row, col, visited):
            if (row, col) in visited:
                return
            visited.add((row, col))
            for i, j in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
                r, c = row + i, col + j
                if 0 <= r < m and 0 <= c < n and heights[r][c] >= heights[row][col]:
                    dfs(r, c, visited)
     
        for i in range(m):
            dfs(i, 0, pacific)
            dfs(i, n - 1, atlantic)
        
        for i in range(n):
            dfs(0, i, pacific)
            dfs(m - 1, i, atlantic)
        
        return list(pacific & atlantic)